package com.hrzyit.base.ui.adapter

import android.graphics.Rect
import android.support.v7.widget.RecyclerView
import android.view.View

/**
 * RecycleView GridLayoutManager 中单元格间距
 * <p>
 *     @param spanCount GridLayoutManger 列数量
 *     @param spacing   每个单元格的左、右、下的空白量：px
 *     @param topSpacing  每个单元格上的空白量：px
 *     @param includeEdge   是否包含边界
 * </p>
 * @author YangWei
 * @date 2019/4/17
 */
class BaseGridSpacingItemDecoration(
    var spanCount: Int, var spacing: Int, var topSpacing: Int, var includeEdge: Boolean
) : RecyclerView.ItemDecoration() {

    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
        super.getItemOffsets(outRect, view, parent, state)

        // item position
        val position = parent!!.getChildAdapterPosition(view)

        // item column 取模
        val column = position % spanCount

        when (includeEdge) {
            true -> {
                // spacing - column * ((1f / spanCount) * spacing)
                outRect!!.left = spacing - column * spacing / spanCount

                // (column + 1) * ((1f / spanCount) * spacing)
                outRect.right = (column + 1) * spacing / spanCount

                // top edge
                outRect.top = if (position < spanCount) {
                    topSpacing
                } else {
                    outRect.top
                }

                // item bottom
                outRect.bottom = spacing
            }
            else -> {
                // column * ((1f / spanCount) * spacing)
                outRect!!.left = column * spacing / spanCount
                // spacing - (column + 1) * ((1f /    spanCount) * spacing)
                outRect.right = spacing - (column + 1) * spacing / spanCount
                // item top
                outRect.top = if (position >= spanCount) {
                    topSpacing
                } else {
                    outRect.top
                }

            }
        }

    }
}